package com.fks.fks_service.controller;

import com.fks.fks_service.base.JsonResult;
import com.fks.fks_service.base.ResultCode;
import com.fks.fks_service.mapper.*;
import com.fks.fks_service.pojo.*;
import com.fks.fks_service.utils.DateUtils;
import com.fks.fks_service.utils.JwtTokenUtil;
import io.jsonwebtoken.Claims;
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.*;

@RestController
@Transactional//开启事务回滚
@Api(tags = "订单模块")
public class ShopOrderController {

    @Autowired
    ShopOrderMapper shopOrderMapper;

    @Autowired
    ShopMapper shopMapper;

    @Autowired
    UserDBMapper userDBMapper;

    @Autowired
    AdminMapper adminMapper;

    @ApiImplicitParams({
            @ApiImplicitParam(name = "token",value = "认证令牌",required = true,paramType = "header"),
            @ApiImplicitParam(name = "jwtRefreshToken",value = "是否重置认证令牌",required = true,paramType = "header"),
            @ApiImplicitParam(name = "shopId",value = "商品id",required = true,paramType = "param"),
            @ApiImplicitParam(name = "price",value = "价格",required = true,paramType = "param"),
            @ApiImplicitParam(name = "notes",value = "备注",required = true,paramType = "param"),
    })
    @ApiOperation(value = "提交订单", notes = "提交订单")
    @ApiResponses(value = {
            @ApiResponse(code = 200, message = "成功", response = String.class)
    })
    @PostMapping("/api/addShopOrder")
    public synchronized JsonResult addShopOrder(HttpServletRequest request){
        //校验参数
        String token = request.getHeader("token");
        if (token==null){
            return JsonResult.error(ResultCode.param_is_null,"缺少参数");
        }
        //获取用户id
        Claims tokenClaims = JwtTokenUtil.getClaims(token);
        int userId = Integer.parseInt(String.valueOf(tokenClaims.get("userId")));
        //权限判断-用户
        String accountType = String.valueOf(tokenClaims.get("accountType"));
        if (!"user".equals(accountType)){
            return JsonResult.error(ResultCode.param_is_null,"权限不足");
        }
        String price = request.getParameter("price");
        String notes = request.getParameter("notes");
        if (request.getParameter("shopId")==null){
            return JsonResult.error(ResultCode.param_is_null,"缺少参数");
        }else if (price==null){
            return JsonResult.error(ResultCode.param_is_null,"缺少参数");
        }else if (notes==null){
            return JsonResult.error(ResultCode.param_is_null,"缺少参数");
        }
        int shopId = Integer.parseInt(request.getParameter("shopId"));

        //获取商品信息
        ShopDB shop = shopMapper.getShop(shopId);
        if (shop==null){
            return JsonResult.error(2000,"商品不存在");
        }
        //获取用户信息
        UserDB user = userDBMapper.getUserById(userId);

        //生成订单号
        Random random = new Random();
        String orderno = "";
        long txTime = System.currentTimeMillis()+86400000;
        txTime = txTime/100;
        int number = random.nextInt(10);
        int number2 = random.nextInt(10);
        int head = 190000+userId;
        orderno=head+String.valueOf(txTime)+String.valueOf(number)+String.valueOf(number2);

        //设置订单信息
        ShopOrder shopOrder = new ShopOrder();
        shopOrder.setOrderNo(orderno);
        shopOrder.setUid(userId);
        shopOrder.setRealName(user.getRealName());
        shopOrder.setRealAge(user.getRealAge());
        shopOrder.setRealGender(user.getRealGender());
        shopOrder.setShopId(shopId);
        shopOrder.setShopTitle(shop.getTitle());
        shopOrder.setShopIntroduction(shop.getIntroduction());
        shopOrder.setShopBannerImages(shop.getBannerImages());
        shopOrder.setShopDetailImages(shop.getDetailImages());
        shopOrder.setShopScore(shop.getPrice());
        shopOrder.setCreateTime(DateUtils.getNowTime());
        shopOrder.setStatus("0");
        shopOrder.setCancellationReason("");
        shopOrder.setIsDelete("0");
        shopOrder.setNotes("");
        shopOrder.setAdminNotes("");
        shopOrder.setCategoryName1(shop.getCategoryName1());
        shopOrder.setCategoryName2(shop.getCategoryName2());
        shopOrder.setCategoryName3(shop.getCategoryName3());
        shopOrder.setComment("");
        shopOrder.setNotes(notes);
        shopOrderMapper.addShopOrder(shopOrder);

        shopOrder = shopOrderMapper.getShopOrderId(shopOrder.getOrderNo());

        return JsonResult.success("提交订单成功").data(shopOrder);
    }

    @ApiImplicitParams({
            @ApiImplicitParam(name = "token",value = "认证令牌",required = true,paramType = "header"),
            @ApiImplicitParam(name = "jwtRefreshToken",value = "是否重置认证令牌",required = true,paramType = "header"),
            @ApiImplicitParam(name = "shopOrderId",value = "订单id",required = true,paramType = "param"),
            @ApiImplicitParam(name = "notes",value = "备注",required = true,paramType = "param"),
    })
    @ApiOperation(value = "修改客服备注", notes = "修改客服备注")
    @ApiResponses(value = {
            @ApiResponse(code = 200, message = "成功", response = String.class)
    })
    @PostMapping("/api/updateNotes")
    public JsonResult updateNotes(HttpServletRequest request){
        String token = request.getHeader("token");
        if (token==null){
            return JsonResult.error(ResultCode.param_is_null,"缺少参数");
        }
        //获取管理员id
        Claims tokenClaims = JwtTokenUtil.getClaims(token);
        int merchantUserId = Integer.parseInt(String.valueOf(tokenClaims.get("userId")));
        //权限判断-商家
        String accountType = String.valueOf(tokenClaims.get("accountType"));
        if (!"merchantUser".equals(accountType)){
            return JsonResult.error(ResultCode.param_is_null,"权限不足");
        }
        String shopOrderId = request.getParameter("shopOrderId");
        String notes = request.getParameter("notes");
        if (shopOrderId==null){
            return JsonResult.error(ResultCode.param_is_null,"缺少参数");
        }else if (notes==null){
            return JsonResult.error(ResultCode.param_is_null,"缺少参数");
        }

        shopOrderMapper.updateAdminNotes(Integer.valueOf(shopOrderId),notes);

        return JsonResult.success("修改客服备注成功");
    }


    @ApiImplicitParams({
            @ApiImplicitParam(name = "token",value = "认证令牌",required = true,paramType = "header"),
            @ApiImplicitParam(name = "jwtRefreshToken",value = "是否重置认证令牌",required = true,paramType = "header"),
            @ApiImplicitParam(name = "shopId",value = "商品id",required = true,paramType = "param"),
    })
    @ApiOperation(value = "获取用户订单相关信息", notes = "获取用户订单相关信息")
    @ApiResponses(value = {
            @ApiResponse(code = 200, message = "成功", response = String.class)
    })
    @PostMapping("/api/getUserShopOrderInformation")
    public JsonResult getUserShopOrderInformation(HttpServletRequest request){
        String token = request.getHeader("token");
        String shopId = request.getParameter("shopId");//商品id
        if (token==null){
            return JsonResult.error(ResultCode.param_is_null,"缺少参数");
        }else if (shopId==null){
            return JsonResult.error(ResultCode.param_is_null,"缺少参数");
        }
        Claims tokenClaims = JwtTokenUtil.getClaims(token);
        int userId = Integer.parseInt(String.valueOf(tokenClaims.get("userId")));
        Map<String, Object> map = new HashMap<>();
        //获取商品信息
        ShopDB shop = shopMapper.getShop(Integer.valueOf(shopId));
        map.put("shopInformation",shop);


        return JsonResult.success("获取用户订单相关信息成功").data(map);
    }

    @ApiImplicitParams({
            @ApiImplicitParam(name = "token",value = "认证令牌",required = true,paramType = "header"),
            @ApiImplicitParam(name = "jwtRefreshToken",value = "是否重置认证令牌",required = true,paramType = "header"),
            @ApiImplicitParam(name = "page",value = "当前页",required = true,paramType = "param"),
            @ApiImplicitParam(name = "pageSize",value = "每页数量",required = true,paramType = "param"),
            @ApiImplicitParam(name = "status",value = "订单状态（如果status为null，查询全部，如果不为null，根据status查询）",required = false,paramType = "param")
    })
    @ApiOperation(value = "用户获取订单列表", notes = "用户获取订单列表")
    @ApiResponses(value = {
            @ApiResponse(code = 200, message = "成功", response = ShopOrder.class)
    })
    @PostMapping("/api/getUserOrderList")
    public JsonResult getUserOrderList(HttpServletRequest request){
        String token = request.getHeader("token");
        if (token==null){
            return JsonResult.error(ResultCode.param_is_null,"缺少参数");
        }
        //获取用户id
        Claims tokenClaims = JwtTokenUtil.getClaims(token);
        int userId = Integer.parseInt(String.valueOf(tokenClaims.get("userId")));

        if (request.getParameter("page")==null || request.getParameter("pageSize")==null) {
            return JsonResult.error(ResultCode.param_is_null,"缺少参数");
        }
        int page = Integer.parseInt(request.getParameter("page"));
        int pageSize = Integer.parseInt(request.getParameter("pageSize"));
        if (page == 0){
            page = 1;
        }
        if (pageSize == 0) {
            pageSize = 10;
        }
        //获取查询条件
        String status = request.getParameter("status");
        List<ShopOrder> orderList = new ArrayList<>();
        if (status==null||"".equals(status)){
            orderList = shopOrderMapper.getOrderList(userId,(page-1)*pageSize,pageSize);
        }else {
            orderList = shopOrderMapper.getUserOrderListByStatus(userId,(page-1)*pageSize,pageSize,Integer.parseInt(status));
        }
        return JsonResult.success("获取列表成功").data(orderList);
    }


    @ApiImplicitParams({
            @ApiImplicitParam(name = "token",value = "认证令牌",required = true,paramType = "header"),
            @ApiImplicitParam(name = "jwtRefreshToken",value = "是否重置认证令牌",required = true,paramType = "header"),
            @ApiImplicitParam(name = "id",value = "订单id",required = true,paramType = "param"),
    })
    @ApiOperation(value = "用户获取订单详情", notes = "用户获取订单详情")
    @ApiResponses(value = {
            @ApiResponse(code = 200, message = "成功", response = ShopOrder.class)
    })
    @PostMapping("/api/getUserOrder")
    public JsonResult getUserOrder(HttpServletRequest request){
        String token = request.getHeader("token");
        String id = request.getParameter("id");
        if (token==null){
            return JsonResult.error(ResultCode.param_is_null,"缺少参数");
        }else if (id==null){
            return JsonResult.error(ResultCode.param_is_null,"缺少参数");
        }
        //获取用户id
        Claims tokenClaims = JwtTokenUtil.getClaims(token);
        int userId = Integer.parseInt(String.valueOf(tokenClaims.get("userId")));

        ShopOrder order = shopOrderMapper.getShopOrderById(Integer.parseInt(id));
        order.setRealName("****");
        order.setRealAge("****");
        order.setRealGender("****");
        return JsonResult.success("获取订单详情成功").data(order);
    }

    @ApiImplicitParams({
            @ApiImplicitParam(name = "token",value = "认证令牌",required = true,paramType = "header"),
            @ApiImplicitParam(name = "jwtRefreshToken",value = "是否重置认证令牌",required = true,paramType = "header"),
            @ApiImplicitParam(name = "id",value = "订单id",required = true,paramType = "param"),
    })
    @ApiOperation(value = "管理员获取订单详情", notes = "管理员获取订单详情")
    @ApiResponses(value = {
            @ApiResponse(code = 200, message = "成功", response = ShopOrder.class)
    })
    @PostMapping("/api/getMerchantUserOrder")
    public JsonResult getMerchantUserOrder(HttpServletRequest request){
        String token = request.getHeader("token");
        String id = request.getParameter("id");
        if (token==null){
            return JsonResult.error(ResultCode.param_is_null,"缺少参数");
        }else if (id==null){
            return JsonResult.error(ResultCode.param_is_null,"缺少参数");
        }
        //获取用户id
        Claims tokenClaims = JwtTokenUtil.getClaims(token);
        int merchantUserId = Integer.parseInt(String.valueOf(tokenClaims.get("userId")));

        ShopOrder order = shopOrderMapper.getShopOrderById(Integer.parseInt(id));
        UserDB user = userDBMapper.getUserById(order.getUid());

        return JsonResult.success("获取订单详情成功").data(order);
    }

    @ApiImplicitParams({
            @ApiImplicitParam(name = "token",value = "认证令牌",required = true,paramType = "header"),
            @ApiImplicitParam(name = "jwtRefreshToken",value = "是否重置认证令牌",required = true,paramType = "header"),
            @ApiImplicitParam(name = "page",value = "当前页",required = true,paramType = "param"),
            @ApiImplicitParam(name = "pageSize",value = "每页数量",required = true,paramType = "param"),
            @ApiImplicitParam(name = "id",value = "订单id或采购单id",required = false,paramType = "param"),
            @ApiImplicitParam(name = "shopTitle",value = "商品名称",required = false,paramType = "param"),
            @ApiImplicitParam(name = "status",value = "状态--  -1、已退款  0、待支付  1、待服务  2、已完结,为null查全部状态",required = false,paramType = "param"),
    })
    @ApiOperation(value = "管理员获取订单列表", notes = "管理员获取订单列表")
    @ApiResponses(value = {
            @ApiResponse(code = 200, message = "成功", response = ShopOrder.class)
    })
    @PostMapping("/api/getMerchantUserOrderList")
    public Map<String, Object> getMerchantUserOrderList(HttpServletRequest request){
        String token = request.getHeader("token");
        if (token==null){
            return JsonResult.error(ResultCode.param_is_null,"缺少参数");
        }
        //获取用户id
        Claims tokenClaims = JwtTokenUtil.getClaims(token);
        int userId = Integer.parseInt(String.valueOf(tokenClaims.get("userId")));
        //获取管理员对应商家id
        Admin admin = adminMapper.getById(userId);
        int adminId = admin.getId();

        if (request.getParameter("page")==null || request.getParameter("pageSize")==null) {
            return JsonResult.error(ResultCode.param_is_null,"缺少参数");
        }
        int page = Integer.parseInt(request.getParameter("page"));
        int pageSize = Integer.parseInt(request.getParameter("pageSize"));
        if (page == 0){
            page = 1;
        }
        if (pageSize == 0) {
            pageSize = 10;
        }
        //获取查询条件
        String id = request.getParameter("id");
        String shopTitle = request.getParameter("shopTitle");
        String status = request.getParameter("status");
        if (id==null||id==""){
            id="0";
        }
        if (shopTitle==null){
            shopTitle="";
        }
        int total = 0;
        List<ShopOrder> orderList = new ArrayList<>();
        if(status==null||"".equals(status)){
            total = shopOrderMapper.getOrderListByStatusNumber(adminId,Integer.valueOf(id),shopTitle);

            orderList = shopOrderMapper.getOrderListByStatus(adminId,Integer.valueOf(id),shopTitle
                    ,page,pageSize);
        }else {
            total = shopOrderMapper.getOrderListByStatusNumber2(adminId,Integer.valueOf(id),shopTitle,status);

            orderList = shopOrderMapper.getOrderListByStatus2(adminId,Integer.valueOf(id),shopTitle
                    ,page,pageSize,status);
        }

        Map<String, Object> map = new HashMap<>();
        map.put("code",200);
        map.put("total",total);
        map.put("msg","获取列表成功");
        map.put("data",orderList);
        return map;
    }

    @ApiImplicitParams({
            @ApiImplicitParam(name = "token",value = "认证令牌",required = true,paramType = "header"),
            @ApiImplicitParam(name = "jwtRefreshToken",value = "是否重置认证令牌",required = true,paramType = "header"),
            @ApiImplicitParam(name = "id",value = "订单id",required = true,paramType = "param"),
    })
    @ApiOperation(value = "删除订单", notes = "删除订单")
    @ApiResponses(value = {
            @ApiResponse(code = 200, message = "成功", response = String.class)
    })
    @PostMapping("/api/deleteOrder")
    public JsonResult deleteOrder(HttpServletRequest request){
        String token = request.getHeader("token");
        if (token==null){
            return JsonResult.error(ResultCode.param_is_null,"缺少参数");
        }
        String id = request.getParameter("id");
        shopOrderMapper.deleteOrder(Integer.parseInt(id));
        return JsonResult.success("删除成功");
    }



}
